<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch">

      <!--根据LLM 检索-->
      <el-form-item prop="llm">
        <el-select v-model="queryParams.llm" placeholder="Select LLM" clearable>
          <el-option v-for="dict in dict.type.llm_model" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <!--根据Prompt Type 检索-->
      <el-form-item prop="promptId">
        <el-select v-model="queryParams.promptId" placeholder="Select Prompt" clearable>
          <el-option v-for="dict in promptList" :key="dict.identifier" :label="dict.identifier" :value="dict.id" />
        </el-select>
      </el-form-item>

      <!--Select LLM Lab Status-->
      <el-form-item prop="status">
        <el-select v-model="queryParams.status" placeholder="Select Status" clearable>
          <el-option v-for="dict in dict.type.lab_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">Search</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">Reset</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['ade:llmlab:add']">New</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-document" size="mini" @click="gotoResult"
          v-hasPermi="['ade:llmlab:add']">ADE LLM Lab Result</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="llmlabList" size="mini">
      <el-table-column label="ID" width="60" align="center" prop="id" />
      <el-table-column label="Algorithm" prop="algorithm" width="150" align="left" show-overflow-tooltip />
      <el-table-column label="LLM" width="140" align="center" prop="llm">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.llm_model" :value="scope.row.llm" />
        </template>
      </el-table-column>
      <el-table-column label="Prompt Type" width="100" align="left" prop="promptType" show-overflow-tooltip>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.prompt_type" :value="scope.row.promptType" />
        </template>
      </el-table-column>
      <el-table-column label="Prompt" width="150" align="left" prop="promptId" :formatter="formatPromptName"
        show-overflow-tooltip />

      <el-table-column label="Standard Status" width="130" align="center" prop="standardStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.status" :value="scope.row.standardStatus" />
        </template>
      </el-table-column>

      <el-table-column label="Include Sources" align="left" prop="includeSources" show-overflow-tooltip />
      <el-table-column label="Exclude Sources" align="left" prop="excludeSources" show-overflow-tooltip />

      <el-table-column label="Status" width="90" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.lab_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="Progress" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.finished || 0 }} / {{ scope.row.total || 0 }}
        </template>
      </el-table-column>

      <el-table-column label="Remark" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="Actions" width="150" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === 'running' || scope.row.status === 'failed' || scope.row.status === 'success'"
            size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)"
            v-hasPermi="['ade:llmlab:edit']"></el-button>
          <el-button v-if="scope.row.status === 'ready'" size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)" v-hasPermi="['ade:llmlab:edit']"></el-button>
          <el-button v-if="scope.row.status === 'ready' || scope.row.status === 'failed'" size="mini" type="text"
            icon="el-icon-position" @click="handleExecute(scope.row)" v-hasPermi="['ade:llmlab:edit']"></el-button>
          <el-button
            v-if="scope.row.status === 'failed' || scope.row.status === 'success' || scope.row.status === 'ready'"
            size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['ade:llmlab:remove']"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改Ade LLM Labs对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="55%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" size="mini" label-position="left" label-width="130px">
        <!--算法名称-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="Algorithm" prop="algorithm">
              <el-input v-model="form.algorithm" placeholder="Pls input algorithm name" style="width: 250px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--选择大模型-->
            <el-form-item label="LLM" prop="llm">
              <el-select v-model="form.llm" placeholder="Select LLM" clearable style="width: 250px;">
                <el-option v-for="dict in dict.type.llm_model" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <!--选择提示词类型-->
            <el-form-item label="Prompt Type" prop="promptType">
              <el-select v-model="form.promptType" placeholder="Select Prompt Type" @change="handleChange"
                style="width: 250px;">
                <el-option v-for="dict in dict.type.prompt_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--选择提示词-->
            <el-form-item label="Prompt" prop="promptId">
              <el-select v-model="form.promptId" placeholder="Select Prompt" style="width: 250px;">
                <el-option v-for="dict in prompts" :key="dict.id" :label="dict.identifier" :value="dict.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col></el-row>

        <!--RAG相关配置-->
        <el-row :gutter="20" v-show="form.promptType === 'RAG'">
          <el-col :span="12">
            <!--选择 ADE 库-->
            <el-form-item label="ADE KB" prop="adekbid">
              <el-select v-model="form.ragConfigObj.adekbid" placeholder="Select ADE KB" size="mini" clearable>
                <el-option v-for="dict in adekbs" :key="dict.id" :label="dict.name" :value="dict.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="Chunk Type" prop="chunk">
              <el-select v-model="form.ragConfigObj.chunkType" placeholder="Select Chunk Type" size="mini" clearable
                style="width: 250px;">
                <el-option v-for="dict in dict.type.chunk_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-show="form.promptType === 'RAG'">
          <el-col :span="12">
            <el-form-item label="Sim Threhold" prop="simProperty">
              <el-input v-model="form.ragConfigObj.simScoreThreshold" placeholder="Sim Threshold" size="mini"
                style="width: 250px;" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="TopN" prop="topNs">
              <el-input-number v-model="form.ragConfigObj.topN" placeholder="TopN" size="mini" :min="0" :max="10"
                style="width: 250px;" />
            </el-form-item>
          </el-col>
        </el-row>


        <!--选择标准集的状态-->
        <el-form-item label="Standard Status" prop="standardStatus">
          <el-select v-model="form.standardStatus" placeholder="Select Standard Status" clearable style="width: 250px;">
            <el-option v-for="dict in dict.type.status" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <!--选择纳入源标准-->
        <el-form-item label="Include Sources" prop="includeSources">
          <el-select v-model="form.includeSources" multiple placeholder="Pls select sources" style="width: 90%;"
            clearable>
            <el-option v-for="dict in dict.type.emr_source" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <!--选择排除源标准-->
        <el-form-item label="ExcludeSource" prop="excludeSource">
          <el-select v-model="form.excludeSources" placeholder="Pls select sources" multiple style="width: 90%;"
            clearable>
            <el-option v-for="dict in dict.type.emr_source" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <!--输入备注信息-->
        <el-form-item label="Remark" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="Pls input remark..." />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">Confirm</el-button>
        <el-button @click="cancel">Cancel</el-button>
      </div>
    </el-dialog>



    <!--ADE llm Lab Detail-->
    <el-dialog :visible.sync="showDialog" @close="handClose()" width="80%" :title="detailTitle">
      <adellmlab-detail-dialog v-if="selectedId" :id="selectedId" />
    </el-dialog>

  </div>
</template>

<script>
import { listLlmlab, getLlmlab, delLlmlab, addLlmlab, updateLlmlab, executeLlmLab } from "@/api/ade/llmlab";
import { listAllPrompt } from "@/api/ade/prompt";
import { listAllAdebase } from "@/api/ade/adebase";

import AdellmlabDetailDialog from "@/views/ade/llmlab/detail.vue";

export default {
  name: "Llmlab",
  dicts: ['lab_status', 'prompt_type', 'llm_model', 'emr_source', 'status', 'ade_knowledge', 'chunk_type'],
  components: {
    AdellmlabDetailDialog,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // Ade LLM Labs表格数据
      llmlabList: [],
      // Prompt
      prompts: [],
      promptList: {}, //缓存的prompt对象
      adekbs: [], //ADE知识库列表
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        algorithm: null,
        promptType: null,
        llm: null,
        promptId: null,
        status: null,
      },
      // 表单参数
      form: {
        ragConfigObj: {
          adekbid: 1,
          chunkType: 'mark',
          simScoreThreshold: 0.7,
          topN: 5
        },
      },
      // 表单校验
      rules: {
        algorithm: [
          { required: true, message: "Algorithm can not be empty!", trigger: "blur" }
        ],
        promptType: [
          { required: true, message: "Prompt yype can not be empty!", trigger: "change" }
        ],
        llm: [
          { required: true, message: "LLM can not be empty!", trigger: "blur" }
        ],
        promptId: [
          { required: true, message: "Prompt can not be emtpy!", trigger: "blur" }
        ]
      },
      //详情对话框参数
      // 弹出层是否显示
      showDialog: false,
      // 选中的ID
      selectedId: null,
      // 详情对话框标题
      detailTitle: "",
    };
  },
  created() {
    this.getPromptList(); // 获取Prompt列表
    this.getList();
  },
  methods: {

    //跳转到Ade LLM Lab Result页面
    gotoResult() {
      this.$router.push({ path: '/analysis/llmlabresult' });
    },
    //关闭详情对话框
    handClose() {
      this.showDialog = false;
      this.selectedId = null;
    },
    //跳转到详情页面
    handleDetail(row) {
      this.detailTitle = 'ADE LLM LAB-[' + row.algorithm + "] Detail";
      this.selectedId = row.id;
      this.showDialog = true;
    },
    //提交执行
    handleExecute(row) {
      const id = row.id || this.ids
      this.$modal.confirm('Are you sure to execute lab："' + id + '"?').then(() => {
        executeLlmLab(id).then(response => {
          this.$modal.msgSuccess("Execution submitted:" + response.msg);
          this.getList();
        }).catch(() => {
          // this.$modal.msgError("Execution failed");
        });
      });
    },
    formatPromptName(row, column, cellValue) {
      console.log("formatPromptName called with cellValue:", cellValue);
      const prompt = this.promptList[cellValue];
      return prompt ? prompt.identifier : cellValue; // 如果缓存中有Prompt对象，则返回
    },
    /** 获取Prompt列表 */
    getPromptList() {
      var data = { "type": this.form.promptType };
      listAllPrompt(data)
        .then((response) => {
          var list = response.data;
          for (let i = 0; i < list.length; i++) {
            this.promptList[list[i].id] = list[i]; // 缓存Prompt对象
          }
        })
        .catch((error) => {
          this.$message.error("Error fetching prompts:", error);
        });
    },
    handleChange(value) {
      // 当Prompt Type发生变化时，可以在这里添加相应的逻辑
      console.log("Prompt Type changed to:", value);
      this.form.promptId = ''; // 重置Prompt ID
      var data = { "type": value };
      listAllPrompt(data)
        .then((response) => {
          this.prompts = response.data;
        })
        .catch((error) => {
          this.$message.error("Error fetching prompts:", error);
        });

      // 如果Prompt Type是RAG，则获取ADE知识库列表
      if (value === 'RAG') {
        listAllAdebase().then(response => {
          this.adekbs = response.data;
          // 设置默认的ADE知识库
          this.form.ragConfigObj.adekbid = this.adekbs.length > 0 ? this.adekbs[0].id : 1;
        });
      } else {
        this.adekbs = [];
        this.form.ragConfigObj.adekbid = 1; // 重置为默认值
      }
    },
    /** 查询Ade LLM Labs列表 */
    getList() {
      this.loading = true;
      listLlmlab(this.queryParams).then(response => {
        this.llmlabList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        algorithm: null,
        promptType: null,
        llm: null,
        promptId: null,
        includeSources: null,
        excludeSources: null,
        standardStatus: null,
        finished: null,
        total: null,
        status: null,
        remark: null,
        createBy: null,
        ragConfig: null,
        createTime: null,
        ragConfigObj: {
          adekbid: 1,
          chunkType: 'mark',
          simScoreThreshold: 0.7,
          topN: 5
        }
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "New ADE Identification Experiment";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getLlmlab(id).then(response => {
        this.form = response.data;

        this.form.includeSources = this.form.includeSources ? this.form.includeSources.split('#') : [];
        this.form.excludeSources = this.form.excludeSources ? this.form.excludeSources.split('#') : [];
        this.form.ragConfigObj = JSON.parse(this.form.ragConfig || '{}'); // 将 ragConfig 字符串转换为对象

        this.open = true;
        this.title = "Edit ADE Identification Experiment";
      });
    },
    /** 提交按钮 */
    submitForm() {

      // 将数组转换为字符串
      this.form.includeSources = this.form.includeSources ? this.form.includeSources.join('#') : null;
      this.form.excludeSources = this.form.excludeSources ? this.form.excludeSources.join('#') : null;
      this.form.status = 'ready'; // 默认状态为 'ready'
      this.form.ragConfig = JSON.stringify(this.form.ragConfigObj); // 将 ragConfigObj 赋值给 ragConfig

      console.log("Submitting form:", this.form);

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateLlmlab(this.form).then(response => {
              this.$modal.msgSuccess("Update successful");
              this.open = false;
              this.getList();
            });
          } else {
            addLlmlab(this.form).then(response => {
              this.$modal.msgSuccess("Add successful");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('Are you sure to delete llm lab:"' + ids + '"').then(function () {
        return delLlmlab(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("Delete successful");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ade/llmlab/export', {
        ...this.queryParams
      }, `llmlab_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
